package com.github.yeecode.mybatisdemo.reflect;

import org.apache.ibatis.reflection.property.PropertyTokenizer;

import java.util.Iterator;

/**
 * @author : wushikai
 * <p>
 * date : 2021-01-15
 * PropertyTokenizer使用了迭代器模式实现了递归解析子串，挺巧妙，之后有类似递归的需求可以借鉴一下，代码简单清晰。
 * 属性分隔解析器。
 * 虽然不知道什么时候调用着个东西, 起码知道它能做什么;
 * 解析格式例如：order[0].item[name].firstName这样的表达式，有点类似json表达式，mybatis通过此类提供了表达式解析的能力，在处理嵌套属性时更加方便和通用。
 *
 */
public class MyPropertyTokenizer implements Iterator<PropertyTokenizer> {



    private String name;
    private final String indexedName;
    private String index;
    private final String children;


    /**
    *    数据：order[0].item[name].firstName
     *
     * 解析结果：
     *
     * name=orde
     *
     * indexedName=order[0]
     *
     * index=0
    * */
    public  MyPropertyTokenizer(String fullname) {
        int delim = fullname.indexOf('.');
        if (delim > -1) {
            name = fullname.substring(0, delim);
            children = fullname.substring(delim + 1);
        } else {
            name = fullname;
            children = null;
        }
        indexedName = name;
        delim = name.indexOf('[');
        if (delim > -1) {
            index = name.substring(delim + 1, name.length() - 1);
            name = name.substring(0, delim);
        }
    }

    public String getName() {
        return name;
    }

    public String getIndex() {
        return index;
    }

    public String getIndexedName() {
        return indexedName;
    }

    public String getChildren() {
        return children;
    }

    @Override
    public boolean hasNext() {
        return children != null;
    }


    /*迭代器模式*/
    @Override
    public PropertyTokenizer next() {
        return new PropertyTokenizer(children);
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Remove is not supported, as it has no meaning in the context of properties.");
    }


    @Override
    public String toString() {
        return "MyPropertyTokenizer{" +
                "name='" + name + '\'' +
                ", indexedName='" + indexedName + '\'' +
                ", index='" + index + '\'' +
                ", children='" + children + '\'' +
                '}';
    }

    public static void main(String[] args){


        MyPropertyTokenizer myPropertyTokenizer = new MyPropertyTokenizer("order[0].item[name].firstName");
        System.out.println("myPropertyTokenizer.toString() = " + myPropertyTokenizer.toString());


    }


}
